"use client";

import { Handle, Position } from "@xyflow/react";
import { TypeBadge } from "./my-badge";
import { useState } from "react";
import { ChevronDown, ChevronUp, Play, Loader2 } from "lucide-react";
import { TaskType } from "@/lib/types";
import { statusConfig, taskTypeColors } from "@/lib/const";

export interface ExternalData extends Record<string, string> {
  name: string;
  type: "text" | "image";
  value: string;
  reference: string;
}
export interface CvNodeData extends Record<string, unknown> {
  task: TaskType;
  modelName: string;
  inputs: ExternalData[];
  outputs: ExternalData[];
  status: "idle" | "running" | "success" | "failed";
}

export const ImageDisplay = ({ src, alt }: { src: string; alt: string }) => {
  const [imageError, setImageError] = useState(false);

  if (imageError) {
    return (
      <div className="w-full h-24 bg-muted rounded flex items-center justify-center text-muted-foreground text-xs">
        图片加载失败
      </div>
    );
  }

  return (
    <img
      src={src.startsWith("data:") ? src : `data:image/jpeg;base64,${src}`}
      alt={alt}
      className="w-full h-36 object-cover rounded"
      onError={() => setImageError(true)}
    />
  );
};

// The CvNode component
export default function CvNode({
  data,
  selected,
}: {
  id: string;
  data: CvNodeData;
  selected?: boolean;
}) {
  const { task, modelName, inputs, outputs, status = "idle" } = data; // Removed onExecute from destructuring

  const statusText = statusConfig[status]?.text || "空闲";
  const [expanded, setExpanded] = useState(false);

  return (
    <div className="relative">
      <div
        className={`rounded-lg border-2 shadow-lg p-3 h-28 w-52 transition-all duration-200 ease-in-out ${
          taskTypeColors[task]
        } ${selected ? "border-sky-400 shadow-sky-400/30" : ""}`}
      >
        <Handle
          type="target"
          id="input"
          position={Position.Top}
          className="!bg-slate-400"
        />

        {/* Node header */}
        <div className="flex items-center justify-between mb-2">
          <div className="font-semibold text-sm truncate flex-1">
            {modelName}
          </div>
          {status === "running" ? (
            <Loader2 size={14} className="animate-spin" />
          ) : (
            <Play size={14} />
          )}
        </div>

        {/* Input/Output information */}
        <div className="space-y-1">
          <div className="text-xs text-slate-300 flex items-center">
            <span className="font-medium mr-1.5">输入:</span>
            <div className="flex flex-wrap items-center gap-1">
              {inputs.map((item: ExternalData, index: number) => (
                <TypeBadge key={`input-${index}`} itemType={item.type} />
              ))}
            </div>
          </div>
          <div className="text-xs text-slate-300 flex items-center">
            <span className="font-medium mr-1.5">输出:</span>
            <div className="flex flex-wrap items-center gap-1">
              {outputs.map((item: ExternalData, index: number) => (
                <TypeBadge key={`output-${index}`} itemType={item.type} />
              ))}
            </div>
          </div>
        </div>

        <Handle
          type="source"
          id="output"
          position={Position.Bottom}
          className="!bg-slate-400"
        />
      </div>

      {/* Status and output expansion card */}
      <div className="absolute top-32 left-0 w-full z-10">
        <div
          className={`flex items-center justify-between px-2 py-1 cursor-pointer bg-slate-800 border border-slate-600 rounded-t-lg shadow-md text-slate-200 ${
            expanded ? "rounded-b-none border-b-0" : "rounded-lg"
          }`}
          onClick={() => setExpanded((v) => !v)}
        >
          <span className="text-xs font-medium">{statusText}</span>{" "}
          {expanded ? <ChevronUp size={14} /> : <ChevronDown size={14} />}
        </div>

        {/* Expanded output content */}
        {expanded && (
          <div className="nowheel bg-slate-800 border border-t-0 border-slate-600 rounded-b-lg shadow-md max-h-72 overflow-y-auto text-slate-200">
            {/* Content directly controlled by 'expanded' state */}
            <div className="p-2 pt-0 border-border bg-muted/30 rounded-b-md">
              {status === "success" &&
                data.outputs &&
                data.outputs.length > 0 && (
                  <div className="space-y-1">
                    {data.outputs.map((item, index) => (
                      <div key={`output-item-${index}`} className="text-xs">
                        <div className="flex items-center gap-1 m-1">
                          <TypeBadge itemType={item.type} />
                          {item.name}
                        </div>
                        {item.type === "image" && item.value ? (
                          <ImageDisplay src={item.value} alt={item.name} />
                        ) : item.type === "text" && item.value ? (
                          <div className="h-16 p-2 overflow-auto bg-secondary border rounded text-xs whitespace-pre-wrap break-all">
                            {item.value}
                          </div>
                        ) : (
                          <span className="ml-1 text-muted-foreground">
                            暂无数据
                          </span>
                        )}
                      </div>
                    ))}
                  </div>
                )}
              {status === "success" &&
                (!data.outputs || data.outputs.length === 0) && (
                  <div className="text-xs text-muted-foreground">
                    没有输出数据
                  </div>
                )}
              {status === "failed" && (
                <div className="text-xs text-red-500">执行失败</div>
              )}
              {status === "running" && (
                <div className="text-xs text-blue-500">运行中...</div>
              )}
              {status === "idle" && (
                <div className="text-xs text-muted-foreground">未执行</div>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
